package com.example.demo_3.controtller;


import com.example.demo_3.entity.Blog;
import com.example.demo_3.service.BlogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@CrossOrigin(origins = "http://localhost:5173")
@RestController
public class BlogController {
    @Autowired
    private BlogService blogService;
    //显示所有博客内容
//    @GetMapping("/api/blogs")
//    public List<Blog> getBlogs() {
//        List<Blog> blogs = new ArrayList<Blog>();
//        //调用Service获取所有博客的内容
//        return blogService.findAll();
//    }
    //分页显示博客内容，通过offset limit来进行选择性查询
    //处理分页参数，通过url传递���页信息（page和size），并且设置默认值

    @GetMapping("/api/blogs")
    public ResponseEntity<?> getBlogsByPage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        if (page < 1 || size < 1) {
            return ResponseEntity.badRequest().body("Invalid page or size parameters");
        }
        try {
            List<Blog> blogs = blogService.findByPage(page, size);
            int total = blogService.count();
            return ResponseEntity.ok(Map.of(
                "blogs", blogs,
                "total", total,
                "currentPage", page,
                "pageSize", size
            ));
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("Error fetching blogs");
        }
    }
}
